package shili;

import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable runnable;
    //此处的time，通过毫秒时间戳，表示这个任务具体什么时候执行
    private long time;
    public MyTimerTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay;
    }
    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}


class MyTimer{
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private static Object locker = new Object();
    public MyTimer(){
        //创建线程，负责执行上述队列中的内容
        Thread t = new Thread(()->{
            try {
           while(true ){
               synchronized (locker){
                   while (queue.isEmpty()){
                           locker.wait();
                   }
                   MyTimerTask current = queue.peek();
                   //对比时间
                   //当前时间System.currentTimeMillis()
                   if(System.currentTimeMillis()>=current.getTime()){
                       current.run();
                       queue.poll();
                   }else {
                       //先不执行任务
                       locker.wait(current.getTime() - System.currentTimeMillis());
                   }
               }
           } } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        t.start();
    }
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
            MyTimerTask myTimerTask = new MyTimerTask(runnable,delay);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}


public class Mytime {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(()->{
            System.out.println("3000");
        },3000);
        myTimer.schedule(()->{
            System.out.println("2000");
        },2000);
        myTimer.schedule(()->{
            System.out.println("1000");
        },1000);
    }
}
